<?php
namespace common\components;

use common\library\Common;
use Yii;

class CommonFunc
{
    private $limit = 10000;

    /**
     * 下载excle
     * @param $header
     * @param $data
     * @param $fileName
     */
    public function downloadLog($header, $data, $fileName)
    {
        $fileName = $this->_charset($fileName);
        header("Content-type:application/vnd.ms-excel");
        header("Content-Disposition:attachment;filename=\"" . $fileName . ".xls\"");
        echo "<?xml version=\"1.0\" encoding=\"gbk\"?>\n
            <Workbook xmlns=\"urn:schemas-microsoft-com:office:spreadsheet\"
            xmlns:x=\"urn:schemas-microsoft-com:office:excel\"
            xmlns:ss=\"urn:schemas-microsoft-com:office:spreadsheet\"
            xmlns:html=\"http://www.w3.org/TR/REC-html40\">";
        echo "\n<Worksheet ss:Name=\"" . $fileName . "\">\n<Table>\n";
        $guard = 0;
        foreach ($header as $v) {
            $guard++;
            if ($guard == $this->limit) {
                ob_flush();
                flush();
                $guard = 0;
            }
            echo $this->_addRow($this->_charset($v));
        }

        foreach ($data as $v) {
            $guard++;
            if ($guard == $this->limit) {
                ob_flush();
                flush();
                $guard = 0;
            }
            echo $this->_addRowFormat($this->_charset($v));
        }


        echo "</Table>\n</Worksheet>\n</Workbook>";
    }

    /**
     * 文件下载
     * @param $data
     * @param $fileName
     */
    public function download($data, $fileName)
    {
        $fileName = $this->_charset($fileName);
        header("Content-type:application/vnd.ms-excel");
        header("Content-Disposition:attachment;filename=\"" . $fileName . ".xls\"");
        echo "<?xml version=\"1.0\" encoding=\"gbk\"?>\n
            <Workbook xmlns=\"urn:schemas-microsoft-com:office:spreadsheet\"
            xmlns:x=\"urn:schemas-microsoft-com:office:excel\"
            xmlns:ss=\"urn:schemas-microsoft-com:office:spreadsheet\"
            xmlns:html=\"http://www.w3.org/TR/REC-html40\">";
        echo "\n<Worksheet ss:Name=\"" . $fileName . "\">\n<Table>\n";
        $guard = 0;
        foreach ($data as $v) {
            $guard++;
            if ($guard == $this->limit) {
                ob_flush();
                flush();
                $guard = 0;
            }
            echo $this->_addRow($this->_charset($v));
        }
        echo "</Table>\n</Worksheet>\n</Workbook>";
    }

    /**
     * 导出的excle添加行
     * @param $row
     * @return string
     */
    private function _addRow($row)
    {
        $cells = "";
        foreach ($row as $k => $v) {
            $cells .= "<Cell><Data ss:Type=\"String\">" . $v . "</Data></Cell>\n";
        }
        return "<Row>\n" . $cells . "</Row>\n";
    }

    /**
     * 导出的excle添加格式行
     * @param $row
     * @return string
     */
    private function _addRowFormat($row)
    {
        $cells = "";
        foreach ($row as $k => $v) {

            if ($k == 'Receivable' || $k == 'IncomeInfoFee' || $k == 'IncomePropertyFee' || $k == 'IncomeDeviceFee' || $k == 'IncomeAttachFee' || $k == 'Received'|| $k == 'CollectTVFee' || $k == 'CollectBusinessFee' || $k == 'CollectFireExtinguisherFee' || $k == 'DepostFee' || $k=='Unreceive') {

                $cells .= "<Cell><Data ss:Type=\"Number\">" . $v . "</Data></Cell>\n";

            } else
                $cells .= "<Cell><Data ss:Type=\"String\">" . $v . "</Data></Cell>\n";
        }
        return "<Row>\n" . $cells . "</Row>\n";
    }

    /**
     * 导出的excle格式化数据
     * @param $row
     * @return string
     */
    private function _charset($data)
    {
        if (!$data) {
            return false;
        }
        if (is_array($data)) {
            foreach ($data as $k => $v) {
                $data[$k] = $this->_charset($v);
            }
            return $data;
        }
        return iconv('utf-8', 'GBK//IGNORE', $data);
    }


    /**
     * 根据单个条件查询某个字段值
     * @param $table       表名（全）
     * @param $value       选择字段
     * @param array $where 数组查询条件 key字段value值
     * @return mixed
     */

    static  public function findValue($table, $value,$where)
    {
        if (isset($table) && isset($value) && isset($where)) {
            $w = '';
            foreach ($where as $key => $val) {
                $w = "`" . $key . "`='" . $val . "'";
            }
            $res = Yii::$app->db->createCommand("SELECT `" . $value . "` FROM `" . $table . "` WHERE " . $w)->queryColumn();
            return $res[0];
        }
    }

    /**
    短网址接口
     **/
    public static function _shortUrl($long_url){
//        $api="http://api.t.sina.com.cn/short_url/shorten.json?source=2815391962&url_long=". urlencode($long_url);
//        $rs = json_decode(file_get_contents($api),true);
//        return $rs[0]['url_short'];
       // $response = Common::curl_method('http://sa.sogou.com/gettiny?url='.$long_url,'','get');
        // return $response;
        return Common::shortUrl($long_url);
    }

    /**
     * 判断是否移动设备
     * @return bool
     */
    public static function  isMobile(){
    // 如果有HTTP_X_WAP_PROFILE则一定是移动设备
    if (isset ($_SERVER['HTTP_X_WAP_PROFILE']))
    {
        return true;
    }
// 如果via信息含有wap则一定是移动设备,部分服务商会屏蔽该信息
if (isset ($_SERVER['HTTP_VIA']))
{
    // 找不到为flase,否则为true
    return stristr($_SERVER['HTTP_VIA'], "wap") ? true : false;
}
// 脑残法，判断手机发送的客户端标志,兼容性有待提高
if (isset ($_SERVER['HTTP_USER_AGENT']))
{
    $clientkeywords = array ('nokia',
        'sony',
        'ericsson',
        'mot',
        'samsung',
        'htc',
        'sgh',
        'lg',
        'sharp',
        'sie-',
        'philips',
        'panasonic',
        'alcatel',
        'lenovo',
        'iphone',
        'ipod',
        'blackberry',
        'meizu',
        'android',
        'netfront',
        'symbian',
        'ucweb',
        'windowsce',
        'palm',
        'operamini',
        'operamobi',
        'openwave',
        'nexusone',
        'cldc',
        'midp',
        'wap',
        'mobile'
    );
    // 从HTTP_USER_AGENT中查找手机浏览器的关键字
    if (preg_match("/(" . implode('|', $clientkeywords) . ")/i", strtolower($_SERVER['HTTP_USER_AGENT'])))
    {
        return true;
    }
}
// 协议法，因为有可能不准确，放到最后判断
if (isset ($_SERVER['HTTP_ACCEPT']))
{
    // 如果只支持wml并且不支持html那一定是移动设备
    // 如果支持wml和html但是wml在html之前则是移动设备
    if ((strpos($_SERVER['HTTP_ACCEPT'], 'vnd.wap.wml') !== false) && (strpos($_SERVER['HTTP_ACCEPT'], 'text/html') === false || (strpos($_SERVER['HTTP_ACCEPT'], 'vnd.wap.wml') < strpos($_SERVER['HTTP_ACCEPT'], 'text/html'))))
    {
        return true;
    }
}
return false;
}

    /**
     * 返回年差
     * @param $beginTime
     * @param $endTime
     * @return int
     */
   static function getYearNum($beginTime, $endTime){
        //计算天数
        $timediff = $endTime - $beginTime;
        $days = $timediff / 86400;
        $days = intval($timediff / 86400);

        $months = round($days / 30.5);

        if ($months > 12) {
            $yearsNum = intval($months / 12);
            return $yearsNum;
        } else {
            return 0;
        }
    }


    /**
     * 时间戳差返回月差
     * @param $beginTime
     * @param $endTime
     * @return int
     */
      public static function getMothNum($beginTime, $endTime){
        //计算天数
        $timediff = $endTime - $beginTime;
        $days = $timediff / 86400;
        $days = intval($timediff / 86400);

        $months = intval($days / 30.5);

        $leftDays = ($days - ( 30.5 * $months));

        if($leftDays>=20){
            return $months+1;
        }else{
            return $months;
        }
    }

    /**
     * 日期差 返回相差年月日
     * @param $date1
     * @param $date2
     * @return array
     */
    static public function diffDate($date1, $date2)
    {
        if (strtotime($date1) > strtotime($date2)) {
            $tmp = $date2;
            $date2 = $date1;
            $date1 = $tmp;
        }
        list($Y1, $m1, $d1) = explode('-', $date1);
        list($Y2, $m2, $d2) = explode('-', $date2);
        $Y = $Y2 - $Y1;
        $m = $m2 - $m1;
        $d = $d2 - $d1;
        if ($d < 0) {
            $d += (int)date('t', strtotime("-1 month $date2"));
            $m--;
        }
        if ($m < 0) {
            $m += 12;
            $Y--;
        }
        return array('year' => $Y, 'month' => $m, 'day' => $d);
    }

    /**
     * 金额转人民币大写字符串
     * @param $num
     * @param bool $isCent 是否分值
     * @return string
     */
  static  public function num2rmb($num, $isCent = true){

        if ($isCent) {
            $num = $num / 100;
        }

        $c1 = "零壹贰叁肆伍陆柒捌玖";
        $c2 = "分角圆拾佰仟万拾佰仟亿";
        $num = round($num, 2);
        $num = $num * 100;
        if (strlen($num) > 10) {
            return "oh,sorry,the number is too long!";
        }
        $i = 0;
        $c = "";
        while (1) {
            if ($i == 0) {
                $n = substr($num, strlen($num) - 1, 1);
            } else {
                $n = $num % 10;
            }
            $p1 = substr($c1, 3 * $n, 3);
            $p2 = substr($c2, 3 * $i, 3);
            if ($n != '0' || ($n == '0' && ($p2 == '亿' || $p2 == '万' || $p2 == '圆'))) {
                $c = $p1 . $p2 . $c;
            } else {
                $c = $p1 . $c;
            }
            $i = $i + 1;
            $num = $num / 10;
            $num = (int)$num;
            if ($num == 0) {
                break;
            }
        }
        $j = 0;
        $slen = strlen($c);
        while ($j < $slen) {
            $m = substr($c, $j, 6);
            if ($m == '零圆' || $m == '零万' || $m == '零亿' || $m == '零零') {
                $left = substr($c, 0, $j);
                $right = substr($c, $j + 3);
                $c = $left . $right;
                $j = $j - 3;
                $slen = $slen - 3;
            }
            $j = $j + 3;
        }
        if (substr($c, strlen($c) - 3, 3) == '零') {
            $c = substr($c, 0, strlen($c) - 3);
        } // if there is a '0' on the end , chop it out
        echo   $c . "整";
    }

    /**Curl get
     * @param $url
     * @return mixed
     */
    static public function _httpget($url)
    {
        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30);
        curl_setopt($ch, CURLOPT_TIMEOUT, 10);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_HEADER, false);
        $output = curl_exec($ch);//输出内容
        curl_close($ch);
        return $output;
    }

    /***
     * curl get|post
     * @param $url
     * @param null $params
     * @param bool $ispost
     * @return bool|mixed
     */
   static public function _http($url, $params = null, $ispost = false)
    {
        $httpInfo = array();
        $ch = curl_init();

        curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
        curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows NT 5.1) AppleWebKit/537.22 (KHTML, like Gecko) Chrome/25.0.1364.172 Safari/537.22');
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30);
        curl_setopt($ch, CURLOPT_TIMEOUT, 30);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
        if ($ispost) {
            curl_setopt($ch, CURLOPT_POST, true);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
            curl_setopt($ch, CURLOPT_URL, $url);
        } else {
            if ($params) {
                curl_setopt($ch, CURLOPT_URL, $url . '?' . $params);
            } else {
                curl_setopt($ch, CURLOPT_URL, $url);
            }
        }
        $response = curl_exec($ch);


        if ($response === FALSE) {
            echo "cURL Error: " . curl_error($ch);
            return false;
        }
        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        $httpInfo = array_merge($httpInfo, curl_getinfo($ch));
        curl_close($ch);
        return $response;
    }
/**
 * @param string $url 请求url
 * @param array $params 参数
 * @param string $method
 * @param array $headers header 头文件
 * @return bool|mixed
 */
    static function curl_method($url, $params = [], $method = 'get', $headers = [])
    {
        //对空格进行转义
        $url = str_replace(' ','+',$url);
        $httpInfo = array();
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
        //curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows NT 5.1) AppleWebKit/537.22 (KHTML, like Gecko) Chrome/25.0.1364.172 Safari/537.22');
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_TIMEOUT, 30);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);    // 对认证证书来源的检查
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);    // 从证书中检查SSL加密算法是否存在

        $requestMethod = strtolower($method);
        switch ($requestMethod) {
            case 'post':
                curl_setopt($ch, CURLOPT_POST, TRUE);
                if ($params) {
                    //todo 如果参数是多维的 使用 http_build_query()处理
                    curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
                } else {
                    curl_setopt($ch, CURLOPT_POSTFIELDS, ''); // Don't know why: if not set,  413 Request Entity Too Large
                }
                break;
            case 'get':
                if ($params) {
                    $sep = false === strpos($url, '?') ? '?' : '&';
                    $url .= $sep . http_build_query($params);
                }
                break;
        }
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($ch, CURLINFO_HEADER_OUT, TRUE);
        $response = curl_exec($ch);
        if ($response === FALSE) {
            //echo "cURL Error: " . curl_error($ch);
            return false;
        }
//        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
//        $httpInfo = array_merge($httpInfo, curl_getinfo($ch));
        curl_close($ch);
        return $response;
    }
    /**
     * 拼接url (GET)
     */
    static  function joinUrl($base_url, array $params)
    {
        if (is_array($params)) {
            $sep = false === strpos($base_url, '?') ? '?' : '&';
            $base_url .= $sep . http_build_query($params);
        }
        return $base_url;
    }
    /**
     *  array转xml
     */
    static     function arrayToXml($arr)
    {
        $xml = "<xml>";
        foreach ($arr as $key => $val) {
            if (is_numeric($val)) {
                $xml .= "<" . $key . ">" . $val . "</" . $key . ">";
            } else
                $xml .= "<" . $key . "><![CDATA[" . $val . "]]></" . $key . ">";
        }
        $xml .= "</xml>";
        return $xml;
    }
    /**
     * @param $obj
     * @return array
     * 对象转数组
     */
    static function objToArr($obj){
        $ret = array();
        foreach($obj as $key =>$value){
            if(gettype($value) == 'array' || gettype($value) == 'object'){
                $ret[$key] = objToArr($value);
            }else{
                $ret[$key] = $value;
            }
        }
        return $ret;
    }
    //数值存在 or 不存在的返回值
    static function isset_value(array $data, $key, $default =""){
        if (!empty($data) && isset($data[$key])) {
            return trim($data[$key]);
        } else {
            return $default;
        }
    }

}

?>